import common.globaldefines
from . import mumumanager
import functools

class AndroidDeviceManager(common.globaldefines.ThreadBase):

    _name = "AndroidDeviceManager"

    def __init__(self):
        super().__init__()
        self._mumumgr = mumumanager.MuMuManager()

    def threadFrame(self):
        self._mumumgr.frame()
        return super().threadFrame()
    
    def onHandle(self, op, *args):
        if "StartDevice" == op:
            name = args[0]
            cbfunc = args[1]
            if cbfunc:
                self._mumumgr.startupDevice(name, functools.partial(self.onDeviceStarted, cbfunc))
            import application
            application.g_App.startTimer(10, functools.partial(self.checkDeviceStartup, name))
        return super().onHandle(op, *args)
    
    def onDeviceStarted(self, cbfunc):
        self.pushToMainThread(("ExecuteFunction", cbfunc))

    def getDeviceSerial(self, name: str):
        return self._mumumgr.GetDeviceSerialName(name)
    
    def checkDeviceStartup(self, name):
        import application
        application.g_App.startTimer(10, functools.partial(self.checkDeviceStartup, name))
        devicepid = self._mumumgr.getDeviceProcessID(name)
        DebugPrint("devicepid:", devicepid)
        if self._mumumgr.getDeviceProcessID(name):
            return True
        DebugPrint(f"device {name} not found. startup.")
        self._mumumgr.startupDevice(name, None)
